package com.lfp.controller;

import com.lfp.entities.User;
import com.lfp.vo.Result;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Author lfp
 * @Date 2021/6/10 14:13
 * @Version 1.0
 */
@RestController
@RequestMapping("validate")
public class ValidationController {

    @GetMapping("test")
    public String test(){
        return "success";
    }


    @PostMapping("add")
    public Result addUser(@Validated @RequestBody User user, BindingResult result){
        List errors = new ArrayList<String>();

        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            // 遍历错误信息，返回给前端
            for (ObjectError error : allErrors) {
                errors.add(error.getDefaultMessage());
            }
            return Result.error(errors);
        }else {
            return Result.ok(user);
        }
    }
}
